class GoodsDetail {
    constructor() {
        this.userActions = document.querySelector('.user-actions');
        this.goodsImage = document.querySelector('#goodsImage');
        this.goodsTitle = document.querySelector('#goodsTitle');
        this.currentPrice = document.querySelector('#currentPrice');
        this.originalPrice = document.querySelector('#originalPrice');
        this.discount = document.querySelector('#discount');
        this.goodsDetailImages = document.querySelector('#goodsDetailImages');
        
        this.init();
    }

    init() {
        this.checkLoginStatus();
        this.loadGoodsInfo();
    }

    // 检查登录状态
    checkLoginStatus() {
        const token = localStorage.getItem('token');
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');

        if (token && userInfo) {
            // 已登录状态
            this.userActions.innerHTML = `
                <span>您好，${userInfo.nickname || userInfo.username}！</span>
                <a href="profile.html" class="login-btn">个人中心</a>
                <a href="javascript:void(0)" class="login-btn" onclick="window.goodsDetail.handleLogout()">退出登录</a>
            `;
        } else {
            // 未登录，返回首页
            alert('请先登录！');
            window.location.href = 'index.html';
        }
    }

    // 加载商品信息
    async loadGoodsInfo() {
        // 如果未登录，不加载商品信息
        const token = localStorage.getItem('token');
        if (!token) return;

        // 从URL获取商品ID
        const urlParams = new URLSearchParams(window.location.search);
        const goodsId = urlParams.get('id');

        if (!goodsId) {
            alert('商品ID不存在');
            window.location.href = 'index.html';
            return;
        }

        try {
            const response = await fetch(`http://localhost:8888/goods/item/${goodsId}`);
            const data = await response.json();
            
            if (data.code === 1) {
                this.renderGoodsInfo(data.info);
            } else {
                alert(data.message || '获取商品信息失败');
                window.location.href = 'index.html';
            }
        } catch (error) {
            alert('获取商品信息失败，请检查网络连接');
            console.error('获取商品信息错误：', error);
        }
    }

    // 渲染商品信息
    renderGoodsInfo(info) {
        this.goodsImage.src = info.img_big_logo;
        this.goodsTitle.textContent = info.title;
        this.currentPrice.textContent = `￥${info.current_price}`;
        this.originalPrice.textContent = `￥${info.price}`;

        if (info.is_sale) {
            this.discount.textContent = info.sale_type || '7折';
        } else {
            this.discount.textContent = '暂无折扣';
        }

        // 渲染商品详情图片
        if (info.goods_introduce) {
            // 从商品介绍中提取所有图片
            const imgRegex = /<img.*?src="(.*?)".*?>/g;
            let match;
            let detailImages = '';
            
            while ((match = imgRegex.exec(info.goods_introduce)) !== null) {
                detailImages += `<img src="${match[1]}" alt="商品详情图">`;
            }
            
            this.goodsDetailImages.innerHTML = detailImages;
        }

        // 更新页面标题
        document.title = `${info.title} - 仿站电商平台`;
    }

    // 处理退出登录
    async handleLogout() {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
        
        try {
            const response = await fetch(`http://localhost:8888/users/logout/${userInfo.id}`, {
                headers: {
                    'authorization': localStorage.getItem('token')
                }
            });

            const data = await response.json();
            
            if (data.code === 1) {
                localStorage.removeItem('token');
                localStorage.removeItem('userInfo');
                alert('退出登录成功！');
                window.location.reload();
            } else {
                alert(data.message || '退出登录失败，请重试');
            }
        } catch (error) {
            alert('退出登录失败，请检查网络连接');
            console.error('退出登录错误：', error);
        }
    }
}

// 初始化商品详情页
window.goodsDetail = new GoodsDetail(); 